using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MySqlX.XDevAPI.Common;
using Publicuse.Appication;
using Publicuse.Autofac;
using Publicuse.Entity;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Interface.Extend;
using Publicuse.Util;
using SharpCompress.Common;
using Geekeradmin.Authorize;
using Geekeradmin.Controllers;

namespace Geekeradmin.Controllers
{
  /// <summary>
  /// 角色管理模块
  /// </summary>
  [UserAuthorize("Admin")]
  public class RoleController : BaseController
  {
    public RoleController(
      IAutofaceInstance autoface,
      IMySqlSugarService mySqlSugar,
      IWebHostEnvironment webHost,
      IOptions<DBConnectionOption> options,
      IBaseServiceExt baseServiceExt
    )
      : base(autoface, mySqlSugar, webHost, options, baseServiceExt) { }

    /// <summary>
    /// 获取角色详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("GetListb")]
    public async Task<JsonResult> GetDetail(int Id)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).GetDetail(Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取角色信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpPost("GetList")]
    public async Task<JsonResult> GetList(Role query)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).GetList(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 根据角色名称获取所有信息
    /// </summary>
    /// <param name="rName"></param>
    /// <returns></returns>
    [HttpGet("GetListc")]
    public async Task<JsonResult> GetListc(string rName)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).GetListc(rName);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取所有角色信息
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    [HttpGet("GetListd"), AllowAnonymous]
    public async Task<JsonResult> GetListd(string type)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).GetListd(type);
      return new JsonResult(result);
    }

    /// <summary>
    /// 绑定用户角色信息
    /// </summary>
    /// <param name="saveUserRoles"></param>
    /// <returns></returns>
    [HttpPost("SaveUserRole")]
    public async Task<JsonResult> SaveUserRole(SaveUserRole saveUserRoles)
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .SaveUserRole(saveUserRoles);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取角色信息树形列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("GetTreeList")]
    public async Task<JsonResult> GetTreeList(RoleQuery query)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).GetTreeList(query);
      return new JsonResult(result);
    }

    /// <summary>
    /// 检查角色名称是否存在
    /// </summary>
    /// <param name="rName"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("CheckRoleName"), AllowAnonymous]
    public async Task<JsonResult> CheckRoleName(string rName, string loginUserCode, string Id = "")
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .CheckRoleName(rName, loginUserCode, Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 检查角色编码是否存在
    /// </summary>
    /// <param name="rCode"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpGet("CheckRoleCode"), AllowAnonymous]
    public async Task<JsonResult> CheckRoleCode(string rCode, string loginUserCode, string Id = "")
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .CheckRoleCode(rCode, loginUserCode, Id);
      return new JsonResult(result);
    }

    /// <summary>
    /// 新增修改角色信息
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    [HttpPost("AddOrUpdate")]
    public async Task<JsonResult> AddOrUpdate(Role info)
    {
      CommonResult result = await RoleApplication.GetApplication(this.container).AddOrUpdate(info);
      return new JsonResult(result);
    }

    /// <summary>
    /// 删除角色信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    [HttpGet("Delete")]
    public async Task<JsonResult> Delete(string Id, string loginUserCode, string type = "-9")
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .Delete(Id, loginUserCode, type);
      return new JsonResult(result);
    }

    /// <summary>
    /// 还原角色删除信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    [HttpGet("Reduction"), AllowAnonymous]
    public async Task<JsonResult> Reduction(string Id, string loginUserCode)
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .Reduction(Id, loginUserCode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 获取用户绑定角色信息
    /// </summary>
    /// <param name="uId"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    [HttpGet("GetUserRoleList"), AllowAnonymous]
    public async Task<JsonResult> GetUserRoleList(string uId, string loginUserCode)
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .GetUserRoleList(uId, loginUserCode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 绑定用户角色信息
    /// </summary>
    /// <param name="uId"></param>
    /// <param name="rId"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    [HttpGet("AddRoleToUser"), AllowAnonymous]
    public async Task<JsonResult> AddRoleToUser(string uId, string rId, string loginUserCode)
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .AddRoleToUser(uId, rId, loginUserCode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 绑定多个用户角色信息
    /// </summary>
    /// <param name="uId"></param>
    /// <param name="rId"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    [HttpGet("AddRoleToUsers"), AllowAnonymous]
    public async Task<JsonResult> AddRoleToUsers(string uId, string rId, string loginUserCode)
    {
      CommonResult result = await RoleApplication
        .GetApplication(this.container)
        .AddRoleToUsers(uId, rId, loginUserCode);
      return new JsonResult(result);
    }

    /// <summary>
    /// 导出数据信息
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet("ExportData")]
    public async Task<IActionResult> ExportData([FromQuery] Role query)
    {
      return await Task.Factory.StartNew<IActionResult>(() =>
      {
        string msg = string.Empty;
        MemoryStream ms = new MemoryStream();
        var exportname = "角色信息统计";
        var filepath = "\\template\\report\\role.xls";
        List<Role> roles = new List<Role>();
        this.baseServiceExt.ExcuteCustom(
          db =>
          {
            var exp = query.GetQueryExpression<Role>(null, out msg);
            int tottal = 0;
            var rolelist = db.Queryable<Role>()
              .LeftJoin<Role>((a, b) => a.parentId == b.Id)
              .Where(exp)
              .Select(
                (a, b) =>
                  new
                  {
                    Id = a.Id,
                    rCode = a.rCode,
                    rName = a.rName,
                    parentName = b.rName,
                    status = a.status,
                    Remark = a.Remark,
                    cTime = a.cTime,
                    uTime = a.uTime,
                    parentId = a.parentId,
                    ischecked = false
                  }
              )
              .OrderByDescending(a => a.Id)
              .ToPageList(1, 1000, ref tottal)
              .ToList();
            if (rolelist != null && rolelist.Count > 0)
            {
              foreach (var role in rolelist)
              {
                roles.Add(
                  new Role()
                  {
                    Id = role.Id,
                    rName = role.rName,
                    Remark = role.Remark,
                    parentName = role.parentName,
                    status = role.status,
                    cTime = role.cTime,
                    uTime = role.uTime,
                    rCode = role.rCode
                  }
                );
              }
            }
          },
          out msg
        );
        if (string.IsNullOrEmpty(msg) && roles.Count > 0)
        {
          string webRootPath = webHost.WebRootPath;
          string fileName = webRootPath + filepath;
          ms = RoleExport.ExportData(fileName, exportname, roles, out var msgb);
          if (string.IsNullOrEmpty(msgb) && ms != null)
          {
            return File(ms.ToArray(), "application/ms-excel", exportname + ".xls");
          }
          else
          {
            return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
          }
        }
        else
        {
          return File(new byte[] { }, "application/ms-excel", exportname + ".xls");
        }
      });
    }
  }
}
